<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2019/11/14 14:44
// +----------------------------------------------------------------------
// | Description:  
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\Settings;
use app\admin\service\AdminUserService;
use app\admin\service\LoginService;
use app\admin\service\MenuService;
use app\admin\service\RoleService;
use app\common\controller\BaseController;
use Jrk\Trees;
use think\facade\Cookie;
use think\facade\Session;

class AdminBase extends BaseController
{
     // 模型
     protected  $model;
     // 服务
     protected  $service;
     // 校验
     protected $validate;
     // 登录ID
     protected $admin_id;
     // 登录信息
     protected $admin_info;
     // 权限
     protected $system_auth;
     // 请求参数
     protected $param;

     //
     protected $online;
     //删除日志
     protected $del='';

     protected $middleware = ['CheckLogin']; //使用中间件


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/9
     * @name: initialize
     * @describe:
     */
     public function initialize(){

         parent::initialize();

          // 初始化配置
         $this->initConfig();

         $this->checkLogin();

        //初始化用户信息
         $this->AdminInfo();

         $this->online=AdminUserService::getOne($this->admin_id);
         //用户信息
         $this->assign("admin_info", $this->online);

         $this->menuList();
     }






    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/3
     * @name: index
     * @describe: 获取分页数据
     */
     public function index(){
         //获取分页数据
        if (IS_AJAX){
            return $this->model->getAdminPageData($this->param);
        }
        return $this->fetch();
    }



    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/9
     * @name: del
     * @describe:删除
     */
     public function del(){
        if (IS_AJAX){
            $ids = $this->request->post("ids");

            $this->setGlobals();
            self::$log->setTitle("删除");
            if (is_array($ids)){
                $i=implode(",",$ids);
            }else{
                $i=$ids;
            }
            self::$log->setContent("删除".$this->del."ID：".$i);
            return $this->model->del($ids);
        }
    }



    /**
      * 初始化配置
      * @return void
      * @author Jackhhy
      * @date 2019-11-14
      */
     public function initConfig()
     {
         // 请求参数
         $this->param = $this->request->param();

         // 分页基础默认值
         defined('LIMIT') or define('LIMIT', isset($this->param['limit']) ? $this->param['limit'] : 20);
         defined('PAGE') or define('PAGE', isset($this->param['page']) ? $this->param['page'] : 1);

     }



    /**
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/25
     * @name: checkLogin
     * @describe:检测登录
     */
     public function checkLogin(){
        if(Cookie::has("jrkhhy") && !Session::has(config('app.user_info_session'))){
             //有cookie 但是没有session
             $cookie=Cookie::get("jrkhhy");
             $user=db("admin_user")->where("cookie",$cookie)->find();
             if (empty($user)){
                 Cookie::delete("jrkhhy");
                 return redirect(url("/admin/login/index"));
             }else{
                 //保存用户信息
                 LoginService::storeAdminInfo($user);

                 Session::set("admin_id",$user['id']); //ID
                 Session::set("admin_role_id",$user['role_id']);//角色ID

             }
         }else if(!Cookie::has("jrkhhy") && Session::has(config('app.user_info_session'))){

             //有 session但是没有cookie
             $tokens=parent::makeToken();//生成随机数
             Cookie::set("jrkhhy",$tokens);
             db('admin_user')->where("id",session("admin_id"))->setField('cookie',$tokens);//更新token值
         }

     }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/3
     * @name: AdminInfo
     * @describe:
     */
     public function AdminInfo(){
         $this->admin_info=LoginService::getAdminUserInfo(); //

         $this->admin_id=session("admin_id");
         $this->system_auth=session("admin_role_id");

         //设置全局变量信息
         $GLOBALS['admin_id']=$this->admin_id;
         $GLOBALS['admin_name']= $this->admin_info['nickname'];

     }



    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/13
     * @name: menuList
     * @describe: 左侧菜单列表
     */
     public function menuList(){
         $role_id=$this->online['role_id'];
         $role=new RoleService();
         if ($role_id==1){ //超级管理员
             $data=MenuService::menuList();
             $data=Trees::DeepTree($data);
         }else{
            $info=$role->getOne(['id'=>$role_id]);
            //当前权限组被禁用
            if ($info['status']==2){
                $this->assign("menulist",[]);
                return ;
            }
            $ids=unserialize($info['rule']);
            $data=MenuService::menuList(['id'=>$ids]);
            $data=Trees::DeepTree($data);
         }
         //dump($data);
         $this->assign("menulist",$data);
     }




    /**
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/13
     * @name: setGlobals
     * @describe:设置全局
     */
     public function setGlobals(){
         $setting=new Settings();
         $safe=$setting->getSetting()['safe'];
         if (isset($safe) && (int)$safe['admin_log']==1){ //是否开启网站后台日志
             $GLOBALS['log']=1;
         }else{
             $GLOBALS['log']=0;
         }
     }



    /**
     * @param string $title
     * @param string $content
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/27
     * @name: addLog
     * @describe:添加行为操作日志
     */
     public function addLog($title='',$content=''){
         $this->setGlobals();
         self::$log->setTitle($title);
         self::$log->setContent($content);
     }

    /**
     * @param $content
     * @param $dir
     * @param string $file
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/13
     * @name: Logs
     * @describe:日志记录
     */
    public function Logs($content, $dir='jrk', $file = '')
    {
        if (empty($file)){
            $file=date("Y_m_d",time());
        }
        $file_path = ROOT_PATH.'Logs/'.$dir;
        if (!is_dir($file_path)) {
            mkdir($file_path, 0777, true);
        }
        @file_put_contents(
            $file_path.'/'.$file.'.log',
            date('Y-m-d H:i:s', time()).' '.var_export($content, true)."\r\n",
            FILE_APPEND
        );
    }


    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/10
     * @name: _empty
     * @describe:空操作
     */
    public function _empty()
    {
        return $this->fetch('public/404');
    }





}
